package com.ly.designpatten.prototype;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONReader;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.SerializeWriter;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.json.JacksonJsonParser;

import java.io.*;

/**
 * @Classname DeepPrototype
 * @Description TODO
 * @Date 2020/10/8 10:47
 * @Author 冷心影翼
 */
public class DeepPrototype {
	public static void main(String[] args) throws IOException {
		Sheep sheep1 = deepCopy(new Sheep("A", 1, "b", new Sheep("B", 1, "r", null)));
		Sheep sheep2 = deepCopy(new Sheep("A", 1, "b", new Sheep("B", 1, "r", null)));
		System.out.println(sheep1 == sheep2);
		System.out.println(sheep1.getFriend() == sheep2.getFriend());
		Sheep sheep3 = deepCopyByJson(new Sheep("A", 1, "b", new Sheep("B", 1, "r", null)));
		Sheep sheep4 = deepCopyByJson(new Sheep("A", 1, "b", new Sheep("B", 1, "r", null)));
		System.out.println(sheep3 == sheep4);
		System.out.println(sheep3.getFriend() == sheep4.getFriend());
	}

	public static Sheep deepCopy(Sheep sheep) {
		ByteArrayOutputStream bos = null;
		ObjectOutputStream oos = null;
		ByteArrayInputStream bis = null;
		ObjectInputStream ois = null;
		Sheep sheepCopy = null;
		try {
			 bos = new ByteArrayOutputStream();
			 oos = new ObjectOutputStream(bos);
			 oos.writeObject(sheep);
			 bis = new ByteArrayInputStream(bos.toByteArray());
			 ois = new ObjectInputStream(bis);
			 sheepCopy = (Sheep) ois.readObject();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} finally {
			try {
				bos.close();
				oos.close();
				bis.close();
				ois.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sheepCopy;
	}

	//fastJson <1.txt.2.68有反序列化漏洞
	public static Sheep deepCopyByFastJson(Sheep sheep) {
		String s = JSONObject.toJSONString(sheep);
		Sheep copy =  JSONObject.parseObject(s,Sheep.class);
		return copy;
	}

	public static Sheep deepCopyByJson(Sheep sheep) throws IOException {
		ObjectMapper objectMapper = new ObjectMapper();
		String s = objectMapper.writeValueAsString(sheep);
		Sheep sheepCopy = objectMapper.readValue(s, Sheep.class);
		return sheepCopy;
	}
}
